package com.hzjiteng.newsbymvp.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.JsonSyntaxException;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * okhttputils的工具类
 *
 * @author Administrator
 * @created_time 2016072614:44
 */
public class OkHttpUtils {

    private static final String TAG = "OkHttpUtils";

    private static OkHttpUtils mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mDeliver;

    private OkHttpUtils() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(10, TimeUnit.SECONDS);

        //set cookie enable
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        mDeliver = new Handler(Looper.getMainLooper());
    }

    private synchronized static OkHttpUtils getmInstance() {
        if (mInstance == null)
            mInstance = new OkHttpUtils();
        return mInstance;
    }

    private void getRequst(String url, final ResultCallBack callBack) {
        Request request = new Request.Builder().url(url).build();
        deliverRultCallBack(callBack, request);

    }

    private void postRequest(String url, ResultCallBack callBack, List<Param> params) {
        deliverRultCallBack(callBack, buildPostResuest(url, params));
    }


    private Request buildPostResuest(String url, List<Param> params) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Param param : params) {
            builder.add(param.key, param.value);
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder().url(url).post(requestBody).build();
    }

    private void deliverRultCallBack(final ResultCallBack callBack, Request request) {
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                sendFilCallBack(callBack, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String str = response.body().string();
                    if (callBack.type == String.class) {
                        sendSuccessCallBack(callBack, str);
                    } else {
                        Object obj = JsonUtils.deSerilize(str, callBack.type);
                        sendSuccessCallBack(callBack, obj);
                    }
                } catch (JsonSyntaxException e) {
                    Log.e(TAG, "convert json failure");
                    e.printStackTrace();
                }
            }
        });
    }


    private void sendFilCallBack(final ResultCallBack callBack, final Exception e) {
        mDeliver.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null)
                    callBack.onFailure(e);
            }
        });
    }

    private void sendSuccessCallBack(final ResultCallBack callBack, final Object obj) {
        mDeliver.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null)
                    callBack.onSuccess(obj);
            }
        });
    }

    public static abstract class ResultCallBack<T> {
        Type type;

        public ResultCallBack() {
            this.type = getSupperClassTypeParameter(getClass());
        }

        static Type getSupperClassTypeParameter(Class<?> subClass) {
            Type superclass = subClass.getGenericSuperclass();
            if (superclass instanceof Class) {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterizedType = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
        }

        /**
         * 请求成功
         *
         * @param respose
         */
        public abstract void onSuccess(T respose);

        /**
         * 请求失败
         *
         * @param e
         */
        public abstract void onFailure(Exception e);
    }


    public static class Param {
        String key;
        String value;

        public Param() {
        }

        public Param(String value, String key) {
            this.value = value;
            this.key = key;
        }
    }


    /**
     * 对外接口,get请求
     *
     * @param url
     * @param callBack
     */
    public static void doGet(String url, ResultCallBack callBack) {
        getmInstance().getRequst(url, callBack);
    }

    /**
     * 对外接口,post请求
     *
     * @param url
     * @param callBack
     * @param params
     */
    public static void doPost(String url, ResultCallBack callBack, List<Param> params) {
        getmInstance().postRequest(url, callBack, params);
    }
}
